var express = require('express');
var router = express.Router();
var config = require('../../config/config.js');
var mysql = require('mysql');
var config = require('../../config/config.js');
var db = mysql.createPool({ host: config.host, user: config.user, password: config.password, database: config. database})

/*
router.get('/get', function(req, res) {
    var item = {};

    // 请求文章信息
    function getArticle() {
        return new Promise(function(resolve, reject) {
            db.query(`SELECT *FROM zq_article ORDER BY post_time`, function(err, data) {
                if (err) {
                    reject(err);
                } else {
                    resolve(data)
                }
            })
        })
    }

    function getTag() {
        return new Promise(function(resolve, reject) {
            db.query('SELECT *FROM zq_zq WHERE showTag="1" ORDER BY orderTag', function(err, data) {
                if (err) {
                    reject(err);
                } else {
                    resolve(data)
                }
            })
        })
    }

    getArticle().then(function(data) {
        console.log(data)
        item.articles = data;
        return getTag()
            // res.render('home/index',{
            //  articles:data
            // })
    }, function(err) {
        console.log(err);
        res.status(500).send('database error').end();
    }).then(function(data) {
        console.log(data);
        item.tags = data;
        console.log(item)
        res.render('home/index', {
            item: item
        })
    }, function(err) {
        console.log(err);
        res.status(500).send('database error').end();
    })

})*/

router.get('/', function(req, res) {

    var type = req.query.type || 'index';
    var tag = req.query.tag || '';
    var str = '';

    // 判断是否是首页，首页查询全部文章
    if (type != 'index') {
        str = ' WHERE menu="' + type + '"';
    }

    

    
    var page = {};
    page.pageSize = 5; //每页显示几条
    page.skip = 5; //忽略前面几条
    page.pages = 0; //总页数
    page.page = req.query.page || 1; //当前页


    var items = {};

    // 获取文章总条数
    function getCount() {
        return new Promise(function(resolve, reject) {
            db.query('SELECT count(id) AS count FROM zq_article ' + str, function(err, data) {
                if (err) {
                    reject(err);
                } else {
                    resolve(data[0].count);
                }
            })
        })
    }

    // 获取文章
    function getArticle() {
        return new Promise(function(resolve, reject) {
            var dataArr = [];
            page.pages = Math.ceil(page.count / page.pageSize);
            page.page = Math.min(page.page, page.pages);
            page.page = Math.max(1, page.page);

            page.skip = (page.page - 1) * page.pageSize;

            db.query('SELECT *FROM zq_article ' + str + ' ORDER BY post_time DESC LiMIT ' + page.skip + ',' + page.pageSize, function(err, data) {
                if (err) {
                    reject(err);
                } else {
                    dataArr = data;
                    // console.log(dataArr)
                    // console.log(tag != '')
                    if (tag != '') {
                        for (var i = 0; i < data.length; i++) {
                            (function(){
                                var index = i;
                                var tags =  data[index].tags.split(',');
                                for (var j = 0; j < tags.length; j++) {
                                    // console.log(tags[j])
                                    if(tag == data[index].tags[j]){
                                        dataArr[index].tags = data[index].tags;
                                        console.log(data[index].tags[j])
                                        console.log(data[index])
                                        if(index == data.length-1){
                                            console.log('-----------------------------------')
                                            console.log(dataArr)
                                        }
                                        break;
                                    }
                                }
                            })();
                        }
                    }

                    dataArr.forEach(function(el, index) {
                        (function() {
                            var i = index;
                            var obj = el;
                            // console.log(typeof obj.tags)
                            db.query('SELECT id,tag FROM zq_tag WHERE zq_tag.id in(' + obj.tags + ')', function(err, newData) {

                                if (err) {
                                    reject(err);
                                } else {
                                    dataArr[i].tags = newData;
                                    if (i == dataArr.length - 1) {
                                        resolve(dataArr)
                                    }
                                }
                            })
                        })();
                    });
                }
            })
        })
    }
    // 获取标签
    function getTag() {
        return new Promise(function(resolve, reject) {
            db.query('SELECT *FROM zq_tag WHERE showTag="1" ORDER BY orderTag', function(err, data) {
                if (err) {
                    reject(err);
                } else {
                    resolve(data)
                }
            })
        })
    }

    // 获取菜单
    function getMenu() {
        return new Promise(function(resolve, reject) {
            db.query('SELECT id,menu FROM zq_menu ORDER BY orderMenu ASC', function(err, data) {
                if (err) {
                    reject(err)
                } else {
                    resolve(data)
                }
            })
        })
    }

    // 或者文章总条数
    getCount().then(function(data) {
        page.count = data
        return getArticle() //获取文章数据
    }, function(err) {
        console.log(err);
        res.status(500).send('database error').end();
    }).then(function(data) {

        items.articles = data;
        return getMenu()    //获取导航数据
    }, function(err) {
        console.log(err);
        res.status(500).send('database error').end();
    }).then(function(data) {
        items.menus = data;
        return getTag()     //获取标签数据
    }, function() {
        console.log(err);
        res.status(500).send('database error').end();
    }).then(function(data) {


        items.tags = data;
        // console.log(items)
        res.render('home/index', {
            items: items,
            page: page,
            type: type
        })
    }, function(err) {
        console.log(err);
        res.status(500).send('database error').end();
    })

})

router.use('/api', require('./api.js'));
// router.use('/menu', require('./menu.js'));

module.exports = router
